package com.ruoyi.quartz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
//
//        httpRequestFactory.setConnectionRequestTimeout(30*1000);
//        httpRequestFactory.setReadTimeout(30*3000);
//        httpRequestFactory.setConnectTimeout(30*3000);
//        //修改字符集，否则返回的结果中会出现乱码
//        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
//        for (HttpMessageConverter<?> httpMessageConverter:list){
//            if(httpMessageConverter instanceof StringHttpMessageConverter){
//                ((StringHttpMessageConverter)httpMessageConverter).setDefaultCharset(Charset.forName("utf-8"));
//                break;
//            }
//        }
//        // 添加拦截器，使用 gzip 编码提交
////        ClientHttpRequestInterceptor interceptor = (httpRequest, bytes, execution) -> {
////            httpRequest.getHeaders().set("user-agent",   "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
////            httpRequest.getHeaders().set("accept",  "*/*");
//////            httpRequest.getHeaders().set("accept-encoding", "gzip");   // 使用 gzip 编码提交
////            return execution.execute(httpRequest, bytes);
////        };
//
//
////        restTemplate.getInterceptors().add(interceptor);
        return restTemplate;
    }
}
